package com.incross.dawin.http.parser;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.incross.dawin.objects.AdInfos;
import com.incross.dawin.util.BKLog;

public class BKAdInfoParser {
	public static final String ATTRIBUTE_SKIP = "skip";
	public static final String ATTRIBUTE_COMPLETE = "complete";
	public static final String ATTRIBUTE_FIRST_QUARTILE = "firstQuartile";
	public static final String ATTRIBUTE_MID_POINT = "midpoint";
	public static final String ATTRIBUTE_THIRD_QUARTILE = "thirdQuartile";
	
	private Element mXmlObject;
	
	private BasicInfoParser mBasicInfos;
	private IconInfoParser mIconInfos;
	private MediaFileInfoParser mMediaFileInfos;
	private TrackingInfoParser mTrackingInfos;
	private AdditionalInfoParser mAddInfos;
	
	public BKAdInfoParser(String xmlObject) {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = factory.newDocumentBuilder();
			
			InputStream is = new ByteArrayInputStream(xmlObject.getBytes());
			Document doc = documentBuilder.parse(is);
			
			mXmlObject = doc.getDocumentElement();
			
			is.close();
			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		// Extract tracking events
		mBasicInfos = new BasicInfoParser(mXmlObject);
		if(!mBasicInfos.getAdId().equals("-1") && mXmlObject != null) { // 20141216 mXmlObject가 null인 경우 아래 Element 추출에서 오류가 날 수 있어서 널 체크 구문 추가
			try { // 20141216 널 체크를 하고 왔지만 혹시 모를 오류사항에 대비해 try catch문 삽입함.
				mIconInfos = new IconInfoParser(mXmlObject.getElementsByTagName("Icons"));
				mMediaFileInfos = new MediaFileInfoParser(mXmlObject.getElementsByTagName("MediaFiles"));
				mTrackingInfos = new TrackingInfoParser(mXmlObject.getElementsByTagName("TrackingEvents"));
				mAddInfos = new AdditionalInfoParser();
				
				if(mXmlObject.getElementsByTagName("SnsShareIcons").getLength() > 0) {
					mAddInfos.initSnsShareInfo(mXmlObject.getElementsByTagName("SnsShareIcons"));
				}
				
				if(mXmlObject.getElementsByTagName("TickerAds").getLength() > 0) {
					mAddInfos.initTickerInfo(mXmlObject.getElementsByTagName("TickerAds"));
				}
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public AdInfos parse() {
		return new AdInfos(mBasicInfos, mTrackingInfos, mMediaFileInfos, mIconInfos, mAddInfos);
	}

}
